import request from '../../request/request.js'
Page({
  data: {
    coachInfo: '',
    id: '',
    gender: '',
    avatar: '',
    name: '',
    username: '',
    coachAuth: '',
    age: 0,
    teachAge: 0,
    introduce: ''
  },
  tempFilePaths: [],
  onLoad: function (options) {
    this.getCoach();
  },
  radioHandle(e) {
    this.setData({
      gender:e.detail.value
    })
  },
  changeAvatar: function () {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var avatarSrc = res.tempFilePaths
        wx.uploadFile({
          url: 'http://localhost:8889/app/coach/upload',
          filePath: res.tempFilePaths[0],
          name: 'avatar',
          formData: {
            avatar: avatarSrc,
            coachId: that.data.id
          }, // HTTP 请求中其他额外的 form data
          header: {
            'content-type': 'application/x-www-form-urlencoded', // 默认值
          },
          success: function (res) {
            if (res.statusCode == 200) {
              that.getCoachInfo();
            }
          }
        })
      }
    })
  },
  submit() {
    var that = this;
    console.log(this.data);
    
    request({
      url: 'coach/edit',
      method: 'post',
      data: {
        id: that.data.id,
        gender: that.data.gender,
        name: that.data.name,
        username: that.data.username,
        age: that.data.age,
        teachAge: that.data.teachAge,
        introduce: that.data.introduce
      }
    }).then(res => {
      if (res.data.code == 200) {
        that.getCoachInfo();
      }
    }).catch(err => { })
  },
  /**
   * 获取缓存中的教练资料
   */
  getCoach() {
    var coachInfo = wx.getStorageSync("coachInfo");
    this.setData({
      id: coachInfo.id,
      gender: coachInfo.gender,
      avatar: coachInfo.avatar,
      name: coachInfo.name,
      username: coachInfo.username,
      coachAuth: coachInfo.coachAuth,
      age: coachInfo.age,
      teachAge: coachInfo.teachAge,
      introduce: coachInfo.introduce
    })
  },
  /**
   * 发送请求获取教练资料，并更新缓存
   */
  getCoachInfo() {
    var that = this;
    request({
      url: 'coach/detail',
      method: 'post',
      data: {
        id: that.data.id
      }
    }).then(res => {
      if (res.data.code == 200) {
        this.setData({
          coachInfo: res.data.data
        })
        wx.setStorageSync('coachInfo', res.data.data)
        that.getCoach()
      }
    }).catch(err => { })
  }
});